package com.madixin.madichat.ui.feature.login

import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.madixin.madichat.repository.UserRepository
import com.madixin.madichat.util.PreferencesManager
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.launch

class LoginViewModel(private val preferencesManager: PreferencesManager) : ViewModel() {

    private val userRepository = UserRepository.getInstance(preferencesManager)
    
    private val _loginState = MutableStateFlow<LoginState>(LoginState.Initial)
    val loginState: StateFlow<LoginState> = _loginState

    private val _phoneNumber = MutableStateFlow("")
    val phoneNumber: StateFlow<String> = _phoneNumber

    private val _password = MutableStateFlow("")
    val password: StateFlow<String> = _password

    private val _rememberMe = MutableStateFlow(false)
    val rememberMe: StateFlow<Boolean> = _rememberMe

    fun updatePhoneNumber(phoneNumber: String) {
        _phoneNumber.value = phoneNumber
    }

    fun updatePassword(password: String) {
        _password.value = password
    }

    fun updateRememberMe(rememberMe: Boolean) {
        _rememberMe.value = rememberMe
    }

    fun login() {
        if (_phoneNumber.value.isEmpty() || _password.value.isEmpty()) {
            _loginState.value = LoginState.Error("手机号和密码不能为空")
            return
        }

        _loginState.value = LoginState.Loading

        viewModelScope.launch {
            try {
                val result = userRepository.login(_phoneNumber.value, _password.value)
                result.fold(
                    onSuccess = { token ->
                        if (_rememberMe.value) {
                            userRepository.saveToken(token)
                        }
                        _loginState.value = LoginState.Success
                    },
                    onFailure = { exception ->
                        _loginState.value = LoginState.Error(exception.message ?: "登录失败")
                    }
                )
            } catch (e: Exception) {
                _loginState.value = LoginState.Error("网络请求失败: ${e.message}")
            }
        }
    }

    sealed class LoginState {
        object Initial : LoginState()
        object Loading : LoginState()
        object Success : LoginState()
        data class Error(val message: String) : LoginState()
    }

    fun resetLoginState() {
        _loginState.value = LoginState.Initial
    }
}